package com.scalar.chiptrack.adaptor.jazz;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;

import java.io.BufferedInputStream;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 5 Jan, 2010
 * Time: 12:46:58 PM
 */
public class JazzAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String PROTOCOL_SCHEME_HTTPS   = "https";
    private static final String HOST                    = "online.jazzsemi.com";
    private static final String POST_URI_LOGIN          = "/ebiz/ebiz.auth";

    private static final int DEFAULT_SSL_PORT   = 443;
    public static final String FILE_NAME_WIP    = "JAZZ_WIP_STATUS";
    public static final String FILE_NAME_SHIP   = "JAZZ_SHIP_STATUS";
    public static final String ADAPTOR_NAME     = "JAZZ_FAB";

    private String m_dataOutputDir      = null;
    private Logger m_adaptorLogger      = null;
    private String m_username           = null;
    private String m_password           = null;
    private int    m_adaptor_id         = -1;

    public JazzAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_JAZZ, LOCATION_TYPE_FAB );
            if( vendorAdaptor == null )
            {
                log( "ERROR!! ERROR!! ERROR!! Exception while loading JAZZ Adaptor Username, Password details from database" );
                throw new ScalarException( "Exception while loading JAZZ Adaptor Username, Password details from database" );
            }
            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();
            
            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir,VENDOR_NAME_JAZZ );
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading JAZZ Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading JAZZ Adaptor Username, Password details from database", se );
        }
    }
    public static void main( String[] args ) throws Exception
    {
        new JazzAdaptor().execute();
    }
    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
            //Print the header details
            AdaptorUtils.printHeader(VENDOR_NAME_JAZZ, CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            HTTPConnection connection = login( HOST, DEFAULT_SSL_PORT, m_username, m_password );

            if ( connection != null )
            {
                BufferedInputStream bfReader = null;
                //For DownLoading WipStatus Report
                HTTPResponse rsp = requestWipReport( connection );
                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Wip Status Sheet..." );
                        log( "\tDownloading the Wip Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP, FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Wip Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip Status Sheet" );
                    throw new ScalarException( "Could not create response object of Wip Status Sheet" );
                }

                //For DownLoading ShipStatus Report
                rsp = requestShipReport( connection );
                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Ship Status Sheet..." );
                        log( "\tDownloading the Ship Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_SHIP, FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SHIP, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Ship Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Ship Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Ship Status Sheet" );
                    throw new ScalarException( "Could not create response object of Ship Status Sheet" );
                }
                                               
                // Logging out from JAZZ WEB SITE
                logout( connection );
                bfReader = null;
            }
            else
            {
                log( "Could not able to get the Connection to web site" );
                throw new ScalarException( "Could not able to get the Connection to web site" );
            }
        }
        catch (Exception e )
        {
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
            System.out.println("Exception while trying to connect and read data from "+HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }
    private HTTPConnection login( String host, int port, String username, String password ) throws Exception
    {
        byte[] data         = new byte[1024];

        HTTPConnection conn = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, host, port );

        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );
        
        NVPair defaultHeaders[] = new NVPair[ 8 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "*/*" );
        defaultHeaders[ 1 ] = new NVPair( "Referer", "https://" + host );
        defaultHeaders[ 2 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 3 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 4 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 5 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" );
        defaultHeaders[ 6 ] = new NVPair( "Host", host );
        defaultHeaders[ 7 ] = new NVPair( "Pragma", "no-cache" );
        conn.setDefaultHeaders( defaultHeaders );

        HTTPResponse rsp = conn.Get("/ebiz/");

        NVPair[] formData = new NVPair[ 4 ];
        formData[ 0 ] = new NVPair( "username", username );
        formData[ 1 ] = new NVPair( "password", password );
        formData[ 2 ] = new NVPair( "Submit", "Login" );

        System.out.print( "Trying to Logging in......" );
        log( "Trying to Logging in......" );
        rsp  = conn.Post( POST_URI_LOGIN, formData, defaultHeaders );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/
        //System.out.println("rsp.getEffectiveUR = " + rsp.getEffectiveURI());
        //System.out.println("rsp.getOriginalURI = " + rsp.getOriginalURI() );


        log( "Response from Server: " + rsp.getStatusCode() + " " + rsp.getReasonLine() );
        if ( rsp.getStatusCode() >= 400 )
        {
            System.out.println( "Login failed.. response from server: " + rsp.getStatusCode() );
            log( "Login failed.. response from server: " + rsp.getStatusCode() );
            conn = null;
        }
        log( "Done." );
        return conn;
    }

    private HTTPResponse requestWipReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse rsp = null;

        rsp = conn.Get( "/ebiz/wiptrackv2/wiptrack_query.jsp" );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/
		synchronized( this )
		{
			wait(10000);
		}
        System.out.println( "\t\nSubmitting the request for Wip Staus......" );
        log( "\tSubmitting the request for Wip Staus......" );

        NVPair[] formData = new NVPair[ 4 ];
        formData[ 0 ] = new NVPair( "PARTNUM", "" );
        formData[ 1 ] = new NVPair( "PN_TYPE", "CUSTOMER" );
        formData[ 2 ] = new NVPair( "LOTID", "" );
        formData[ 3 ] = new NVPair( "COMCLASS", "ACTIVE" );
        
        rsp = conn.Post( "/ebiz/wiptrackv2/wiptrack_exec.jsp", formData );
		synchronized( this )
		{
			wait(10000);
		}
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/
        rsp = conn.Get( "/ebiz/wiptrackv2/excelview.jsp" );
        
        return rsp;
    }
    private HTTPResponse requestShipReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse rsp = null;

        rsp = conn.Get( "/ebiz/wiptrackv2/shipment_query.jsp" );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/

        System.out.println( "\t\nSubmitting the request for Ship Staus......" );
        log( "\tSubmitting the request for Ship Staus......" );
		System.out.println("From " + DateUtil.getPreviousDate(6) + " To " + DateUtil.getCurrentDate() );

        NVPair[] formData = new NVPair[ 6 ];
        formData[ 0 ] = new NVPair( "PARTNUM", "" );
        formData[ 1 ] = new NVPair( "PN_TYPE", "CUSTOMER" );
        formData[ 2 ] = new NVPair( "LOTID", "" );
        formData[ 3 ] = new NVPair( "PO_NUM", "" );
        formData[ 4 ] = new NVPair( "START_DATE", DateUtil.getPreviousDate(6) );
        formData[ 5 ] = new NVPair( "END_DATE", DateUtil.getCurrentDate() );

        rsp = conn.Post( "/ebiz/wiptrackv2/shipment_report.jsp" , formData );
		synchronized( this )
		{
			wait(10000);
		}
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/
        rsp = conn.Get( "/ebiz/wiptrackv2/shipment_report_excel.jsp" );

        return rsp;
    }
    /**
     *
     *  Logs out from the JAZZ Web Site
     */
    private void logout( HTTPConnection conn ) throws Exception
    {
        try
        {
            System.out.print( "\n Logging out... " );
            log( "\n Logging out... " );
            HTTPResponse rsp = conn.Get( "/ebiz/common/logoff.jsp" );
            System.out.println( "Successfully logged out from JAZZ Site" );
            log( "Successfully logged out from JAZZ Site" );
            conn = null;
            //rsp = null;
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From JAZZ Site" + ignore);
            throw ignore;
        }
    }
    private void log( String message )
    {
        if ( message == null ) return;
        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

